package models

import (
	"database/sql"
	"go-autocode/utils"
	"strings"
)

type IndexInfo struct {
	IndexId        int
	IndexName      string
	IndexComment   string
	IndexType      string
	IndexColumnId  int
	ColumnId       int
	ColumnName     string
	Sort           string
	Unique         string
	ColumnNameCase string
}

func GetIndexInfos(table_name string) (index_infos []IndexInfo, err error) {
	rows, err := mainDB.Query("SELECT IndexId = ISNULL(KC.[object_id], IDX.index_id) , IndexName = IDX.Name, IndexComment = properties.value , IndexType = ISNULL(KC.type_desc, 'Index') , Index_Column_id = IDXC.index_column_id, ColumnID = C.Column_id , ColumnName = C.Name, Sort = CASE INDEXKEY_PROPERTY(IDXC.[object_id], IDXC.index_id, IDXC.index_column_id, 'IsDescending') WHEN 1 THEN 'DESC' WHEN 0 THEN 'ASC' ELSE '' END, [Unique] = CASE WHEN IDX.is_unique = 1 THEN N'√' ELSE N'×' END FROM sys.indexes IDX INNER JOIN sys.extended_properties properties ON properties.major_id = IDX.object_id AND properties.minor_id = IDX.index_id INNER JOIN sys.index_columns IDXC ON IDX.[object_id] = IDXC.[object_id] AND IDX.index_id = IDXC.index_id LEFT JOIN sys.key_constraints KC ON IDX.[object_id] = KC.[parent_object_id] AND IDX.index_id = KC.unique_index_id INNER JOIN sys.objects O ON O.[object_id] = IDX.[object_id] INNER JOIN sys.columns C ON O.[object_id] = C.[object_id] AND O.type = 'U' AND O.is_ms_shipped = 0 AND IDXC.Column_id = C.Column_id INNER JOIN( SELECT [object_id], Column_id, index_id = MIN(index_id) FROM sys.index_columns GROUP BY [object_id], Column_id) IDXCUQ ON IDXC.[object_id] = IDXCUQ.[object_id] AND IDXC.Column_id = IDXCUQ.Column_id WHERE properties.class = 7 AND o.object_id = object_id(?)", table_name)
	defer rows.Close()
	if err != nil {
		return index_infos, err
	}
	return _IndexInfoRowsToArray(rows)
}

func _IndexInfoRowsToArray(rows *sql.Rows) (models []IndexInfo, err error) {
	for rows.Next() {
		model := IndexInfo{}
		err = rows.Scan(&model.IndexId, &model.IndexName, &model.IndexComment, &model.IndexType, &model.IndexColumnId, &model.ColumnId, &model.ColumnName, &model.Sort, &model.Unique)
		if err != nil {
			return models, err
		}
		if len(model.IndexComment) > 0 {
			model.IndexComment = strings.Replace(model.IndexComment, "\r", "", -1)
			model.IndexComment = strings.Replace(model.IndexComment, "\n", "", -1)
		}
		if len(model.IndexComment) > 0 {
			model.IndexComment = strings.Replace(model.IndexComment, "\r", "", -1)
			model.IndexComment = strings.Replace(model.IndexComment, "\n", "", -1)
		}
		model.ColumnNameCase = model.ColumnName
		utils.ToBigHump(&model.ColumnNameCase)
		models = append(models, model)
	}
	return models, err
}
